package lib.pay;

import lib.Dao.CourseDAO;
import lib.Dao.Dbutil;
import lib.Dao.SchoolDAO;
import lib.Model.Course;
import lib.Model.School;
import lib.wxpay.sdk.WXPayUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lib.pay.HttpRequest;
import lib.servlet.AuthUtil;
import lib.wxpay.sdk.WXPayUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import lib.Dao.TokenDao;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ttop5 on 16-4-22.
 */
@WebServlet(urlPatterns = "/wxprepay", name = "wxprepay")
public class wxprepay extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cid = new String(req.getParameter("cid").getBytes("ISO-8859-1"), "UTF-8");
        String se= (String) req.getSession().getAttribute("se");
        List<Course> courseList=new ArrayList<>();
        Dbutil dbutil = new Dbutil();
        CourseDAO courseDAO=new CourseDAO();

        try {
            //JSONObject userInfo= (JSONObject) req.getSession().getAttribute("info");
            String openId= (String) req.getSession().getAttribute("openid");

            System.out.println(openId);
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

            String timestamp = formatter.format(date)+(int)(Math.random()*9+0);
            System.out.println(timestamp);

            //拼接统一下单地址参数
            Map<String, String> paraMap = new HashMap<String, String>();
            //获取请求ip地址
            String ip = req.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = req.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = req.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = req.getRemoteAddr();
            }
            if (ip.indexOf(",") != -1) {
                String[] ips = ip.split(",");
                ip = ips[0].trim();
            }

            paraMap.put("appid","wx291b25f289a25814");
            paraMap.put("attach",cid);
            paraMap.put("body", "云逸抢课助手-课程余量预约");
            paraMap.put("mch_id", "1565222901");
            paraMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paraMap.put("openid", openId);
            paraMap.put("out_trade_no",timestamp);//订单号
            paraMap.put("spbill_create_ip", ip);
            paraMap.put("total_fee","100");
            paraMap.put("trade_type", "JSAPI");
            paraMap.put("notify_url", "www.eyehelper.top/paied");// 此路径是微信服务器调用支付结果通知路径随意写
            String sign = WXPayUtil.generateSignature(paraMap,"lipeiyuan12138lipeiyuan12138lipe");
            paraMap.put("sign", sign);
            String xml = WXPayUtil.mapToXml(paraMap);//将所有参数(map)转xml格式
            System.out.println(xml);
            // 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
            String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

            String xmlStr = HttpRequest.sendPost(unifiedorder_url, xml);//发送post请求"统一下单接口"返回预支付id:prepay_id

            //以下内容是返回前端页面的json数据
            String prepay_id = "";//预支付id
            if (xmlStr.indexOf("SUCCESS") != 99) {
                Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
                prepay_id = (String) map.get("prepay_id");
                System.out.println(map.toString());
            }
            Map<String, String> payMap = new HashMap<String, String>();
            payMap.put("appId","wx291b25f289a25814");
            payMap.put("timeStamp", WXPayUtil.getCurrentTimestamp()+"");
            payMap.put("nonceStr", WXPayUtil.generateNonceStr());
            payMap.put("signType", "MD5");
            payMap.put("package", "prepay_id=" + prepay_id);
            String paySign = WXPayUtil.generateSignature(payMap, "lipeiyuan12138lipeiyuan12138lipe");
            payMap.put("paySign", paySign);
            System.out.println(payMap.toString());
            System.out.println(paySign);
            //System.out.println();
            courseList= courseDAO.getCid(se,cid);

            req.getSession().setAttribute("cid",cid);
            req.getSession().setAttribute("list", courseList);
            req.getSession().setAttribute("result", payMap);
            //req.getRequestDispatcher("/page/course/pay.jsp").forward(req, resp);

            resp.sendRedirect("/page/course/pay.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
